package com.xw.unification.exception;

import com.xw.unification.interfaces.ResultCodeEnumerable;
import com.xw.unification.interfaces.UnifiedExceptionResolvable;
import lombok.Getter;
import lombok.ToString;

/**
 * 统一检查异常
 *
 * @author qiwei
 * @date 2023-8-10 16:00:00
 * @since v1.0.0
 */
@Getter
@ToString
public class UnifiedException extends Exception implements UnifiedExceptionResolvable {

    private ResultCodeEnumerable resultCodeEnum;
    private int code;
    private String message;
    private Object body;

    public UnifiedException(ResultCodeEnumerable resultCodeEnum) {
        this(resultCodeEnum, resultCodeEnum == null ? null : resultCodeEnum.getMessage(), null);
    }

    public UnifiedException(ResultCodeEnumerable resultCode, Object body) {
        super(resultCode == null ? null : resultCode.getMessage());
        if (resultCode == null) {
            throw new IllegalArgumentException("Result code can not be null");
        }
        this.resultCodeEnum = resultCodeEnum;
        this.code = resultCodeEnum.getCode();
        this.message = resultCode.getMessage();
        this.body = body;
    }

    public UnifiedException(ResultCodeEnumerable resultCodeEnum, String message, Object body) {
        super(message);
        if (resultCodeEnum == null) {
            throw new IllegalArgumentException("Result code can not be null");
        }
        this.resultCodeEnum = resultCodeEnum;
        this.code = resultCodeEnum.getCode();
        this.message = message;
        this.body = body;
    }

    protected UnifiedException(int errorCode, String message, Object body) {
        super(message);
        this.resultCodeEnum = null;
        this.code = errorCode;
        this.message = message;
        this.body = body;
    }

    @Override
    public String getErrorMessage() {
        return message;
    }

    @Override
    public Integer getErrorCode() {
        return code;
    }

    @Override
    public Object getBody() {
        return body;
    }
}
